'use client';

import {usePathname, useRouter, useSearchParams} from 'next/navigation';
import styles from './Search.module.css'
import {SearchIcon} from "lucide-react";
import {useDebouncedCallback} from "use-debounce";

export default function Search({placeholder}: { placeholder: string }) {
    const searchParams = useSearchParams();
    const pathname = usePathname();
    const {replace} = useRouter();

    const handleSearch = useDebouncedCallback((term) => {
        const params = new URLSearchParams(searchParams);
        if (term) {
            params.set('search', term);
        } else {
            params.delete('search');
        }
        replace(`${pathname}?${params.toString()}`);
    }, 500);

    return (
        <div className={styles.container}>
            <label htmlFor="search" className={styles.screenReaderOnly}>
                Поиск
            </label>
            <input
                className={styles.input}
                placeholder={placeholder}
                onChange={(e) => {
                    handleSearch(e.target.value);
                }}
                defaultValue={searchParams.get('search')?.toString()}
            />
            <SearchIcon className={styles.searchIcon}/>
        </div>
    );
}